'use client';

import React, { useState, useMemo } from 'react';

import { BlogFilter } from '@/components/blog/BlogFilter';
import { BlogListItem } from '@/components/blog/components/blog-list-item';
import { Pagination } from '@/components/blog/components/pagination';
import { IllustrationNoContent } from '@/components/illustrations';
import { filterPublishedBlogs } from '@/utils/utils';

const ITEMS_PER_PAGE = 6;

interface FilteredBlogListProps {
    initialBlogs: any[];
}

export function FilteredBlogList({ initialBlogs }: FilteredBlogListProps) {
    // 首先应用时间过滤，只显示已发布的博客
    const publishedBlogs = useMemo(() => {
        return filterPublishedBlogs(initialBlogs);
    }, [initialBlogs]);

    const [blogs] = useState(publishedBlogs);
    const [selectedTag, setSelectedTag] = useState<string | null>(null);
    const [searchQuery, setSearchQuery] = useState('');
    const [currentPage, setCurrentPage] = useState(1);

    const { filteredBlogs, paginatedBlogs, totalPages } = useMemo(() => {
        const filtered = blogs.filter((blog) => {
            const matchesSearch =
                searchQuery === '' ||
                blog.title.toLowerCase().includes(searchQuery.toLowerCase()) ||
                blog.content.toLowerCase().includes(searchQuery.toLowerCase());

            const matchesTag = !selectedTag || blog.tags.includes(selectedTag);

            return matchesSearch && matchesTag;
        });

        const startIndex = (currentPage - 1) * ITEMS_PER_PAGE;
        const endIndex = startIndex + ITEMS_PER_PAGE;
        const paginated = filtered.slice(startIndex, endIndex);
        const totalPages = Math.ceil(filtered.length / ITEMS_PER_PAGE);

        return {
            filteredBlogs: filtered,
            paginatedBlogs: paginated,
            totalPages
        };
    }, [blogs, selectedTag, searchQuery, currentPage]);

    const handlePageChange = (page: number) => {
        setCurrentPage(page);
        window.scrollTo({ top: 0, behavior: 'smooth' });
    };

    const handleSearch = (query: string) => {
        setSearchQuery(query);
        setCurrentPage(1); // 重置到第一页
    };

    const handleTagSelect = (tag: string | null) => {
        setSelectedTag(tag);
        setCurrentPage(1); // 重置到第一页
    };

    return (
        <div>
            <BlogFilter
                onSearch={handleSearch}
                onTagSelect={handleTagSelect}
                selectedTag={selectedTag}
            />

            {paginatedBlogs.length > 0 ? (
                <>
                    <ul className="grid grid-cols-1 gap-10 md:grid-cols-2 border-blue-700">
                        {paginatedBlogs.map((blog, idx) => (
                            <BlogListItem blog={blog} key={idx} />
                        ))}
                    </ul>

                    <Pagination
                        currentPage={currentPage}
                        totalPages={totalPages}
                        onPageChange={handlePageChange}
                    />
                </>
            ) : (
                <div className="grid place-content-center gap-8">
                    <IllustrationNoContent className="size-[30vh]" />
                    <h3 className="text-center text-2xl font-semibold tracking-tight">暂无匹配的Blog</h3>
                </div>
            )}
        </div>
    );
}
